package edu.nf.postlikework.service.consumer;

import edu.nf.postlikework.common.config.RabbitConfig;
import edu.nf.postlikework.mapper.LikeMapper;
import edu.nf.postlikework.mapper.PostMapper;
import edu.nf.postlikework.model.dto.LikeDTO;
import edu.nf.postlikework.model.entity.Like;
import edu.nf.postlikework.model.entity.Post;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author zjl
 * @date 2025/10/13
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = RuntimeException.class)
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(name = RabbitConfig.QUEUE_NAME,durable = "false"),
        exchange = @Exchange(name = RabbitConfig.EXCHANGE_NAME,type = ExchangeTypes.DIRECT),
        key = RabbitConfig.ROUTER_KEY
))
public class LikeSyncConsumer {
    private final LikeMapper likeMapper;
    private final PostMapper postMapper;

    @RabbitHandler
    public void receive(LikeDTO likeDTO){
        //更新点赞表
        if(likeDTO.getLikeStatus()){
            Like like = new Like();
            BeanUtils.copyProperties(likeDTO,like);
            likeMapper.save(like);
        }else{
            likeMapper.delete(likeDTO.getPostId(),likeDTO.getUserId());
        }
        Post post = new Post();
        BeanUtils.copyProperties(likeDTO,post);
        postMapper.update(post);
    }
}
